import React, { memo, useRef, useState } from 'react'
import type { FC, ReactNode, ElementRef } from 'react'
import { BannerLeft, BannerWrapper, BannerRight, BannerControl } from './style'
import { useAppSelect } from '@/store'
import { shallowEqual } from 'react-redux'

import { Carousel } from 'antd'
import classNames from 'classnames'
interface IProps {
  children?: ReactNode
}

const TopBanner: FC<IProps> = () => {
  /* 定义内部数据 */
  /* 绑定轮播图ref */
  const bannerRef = useRef<ElementRef<typeof Carousel>>(null)
  const [currentIndex, setCurrentIndex] = useState(0)
  /* 获取redux中的数据 */
  const { banners } = useAppSelect(
    (state) => ({
      banners: state.recommend.banners
    }),
    shallowEqual
  )
  /* 自定义方法 */
  function handlePreClick() {
    bannerRef.current?.prev()
  }
  function handleNextClick() {
    bannerRef.current?.next()
  }

  function handleBeforeChange(from: any, to: any) {
    setCurrentIndex(to)
  }
  let bgImageUrl = banners[currentIndex]?.imageUrl
  if (bgImageUrl && currentIndex !== 0) {
    bgImageUrl = bgImageUrl + '?imageView&blur=40x20'
  }
  return (
    <BannerWrapper bgImage={bgImageUrl}>
      <div className="banner wrap-v2">
        <BannerLeft>
          <Carousel
            autoplay
            ref={bannerRef}
            effect="fade"
            dots={false}
            beforeChange={handleBeforeChange}
          >
            {banners.map((item: any) => {
              return (
                <div className="banner-item" key={item.imageUrl}>
                  <img className="image" src={item.imageUrl} alt="" />
                </div>
              )
            })}
          </Carousel>
          <ul className="dots">
            {banners.map((item, index) => {
              return (
                <li key={item.imageUrl}>
                  <span
                    className={classNames('item', {
                      active: currentIndex === index
                    })}
                  ></span>
                </li>
              )
            })}
          </ul>
        </BannerLeft>
        <BannerRight></BannerRight>
        <BannerControl>
          <button className="btn left" onClick={handlePreClick}></button>
          <button className="btn right" onClick={handleNextClick}></button>
        </BannerControl>
      </div>
    </BannerWrapper>
  )
}

export default memo(TopBanner)
